package com.hw.nio.channel;


import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;

/**
 * @author 车宏伟
 * @date 2021/1/13 11:31
 * UDP数据传输
 */
public class DatagramChannelTest {

    public static void main(String[] args) {
        System.out.println("qwe");
    }

    @Test
    public void test() throws IOException {
        DatagramChannel channel = DatagramChannel.open();
        channel.bind(new InetSocketAddress(8090));

        ByteBuffer buffer = ByteBuffer.allocate(1024);

        while (true) {
            buffer.clear();
            channel.receive(buffer);
            buffer.flip();
            byte[] arr = new byte[buffer.remaining()];
            buffer.get(arr);
            System.out.println(new String(arr));
            buffer.clear();
            buffer.put("服务器收到了消息，并且给你回复".getBytes());
            buffer.flip();
            channel.send(buffer, new InetSocketAddress("127.0.0.1", 9090));
        }
    }

    @Test
    public void test1() throws IOException {
        DatagramChannel channel = DatagramChannel.open();
        channel.bind(new InetSocketAddress(9090));

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        buffer.put("你好、、服务器".getBytes());
        buffer.flip();
        channel.send(buffer, new InetSocketAddress("127.0.0.1", 8090));

        buffer.clear();
        channel.receive(buffer);
        buffer.flip();
        int i = 0;
        byte[] arr = new byte[buffer.remaining()];
        while (buffer.hasRemaining()) {
            arr[i++] = buffer.get();
        }

        System.out.println("收到服务器消息：" + new String(arr));
    }


}
